import { pageMonitorArticle } from '@/services/api/api-monitor-article';
import { mediaList, platformList } from '@/services/api/api-monitor-linkage';
import { pageMonitorVideoRecordStatistics } from '@/services/api/api-monitor-video';
import { RedoOutlined } from '@ant-design/icons';
import type { ActionType, FormInstance, ProColumns } from '@ant-design/pro-components';
import {
  PageContainer,
  ProForm,
  ProFormCascader,
  ProFormDateRangePicker,
  ProFormRadio,
  ProFormSwitch,
  ProTable,
  QueryFilter,
} from '@ant-design/pro-components';
import { useAccess } from '@umijs/max';
import { Cascader, Space, Tag } from 'antd';
import moment from 'moment';
import RcResizeObserver from 'rc-resize-observer';
import { useEffect, useRef, useState } from 'react';
import DetailsMonitorArticle from './DetailMonitorArticle';
import './PageContainerMonitorArticle.less';
interface PageContainerMonitorArticleProps {}

const PageContainerMonitorArticle: React.FC<PageContainerMonitorArticleProps> = (props) => {
  const access = useAccess();

  const [width, setWidth] = useState(500);

  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();

  const [cascadersSourceData, setCascadersSourceDataState] = useState<
    MonitorData.CascadersSource[]
  >([]);

  const [optionsCascadersSourceData, setOptionsCascadersSourceDataState] = useState<
    MonitorData.CascadersSource[]
  >([]);

  const [optionsPlatformData, setOptionsPlatformData] = useState();

  const [pageMonitorVideoRecordStatisticsData, setPageMonitorVideoRecordStatisticsDataState] =
    useState<MonitorVideoData.VideoRecordPageStatistics[]>([
      // { label: '问题总数', value: '2' },
      // { label: '网站', value: '1' },
      // { label: '电子报纸', value: '1' },
    ]);

  const getCascadersMedia = async () => {
    const res = await mediaList();
    if (res.code === 0) {
      setOptionsCascadersSourceDataState(res.data);
    }
  };

  const getCascadersPlatform = async () => {
    const res = await platformList();
    if (res.code === 0) {
      const list = new Array();
      list.push([{ label: '全部', value: '' }, ...res.data]);
      console.log(list);
      setOptionsPlatformData(...list);
    }
  };
  /**
   * 搜索参数
   */
  const [queryParam, setQueryParamState] = useState({});

  const columns: ProColumns<DatahubRecordData.PretreatmentRecordPage>[] = [
    {
      title: '状态',
      width: 50,
      render: (dom, row) => (
        <>
          <Tag color={row.isViolation == 1 ? 'red' : 'green'}>
            {row.isViolation == 1 ? '问题' : '正常'}
          </Tag>
        </>
      ),
    },
    {
      title: '标题',
      dataIndex: 'title',
      hideInSearch: true,
      ellipsis: true,
      render: (dom, row) => (
        // <DetailMonitorVideo
        //   data={row}
        //   onRefurbish={() => {
        //     actionRef.current?.reload;
        //   }}
        // />
        <>
          <DetailsMonitorArticle details={row} onRefurbish={actionRef.current?.reload} />
          {/* <div>
            <Tag color={row.isViolation==1?"red":"green"}>{row.isViolation==1?"问题":"正常"}</Tag>
            <span style={{ color: '#1677FF' }}>{row?.title}</span>
          </div> */}
        </>
      ),
    },
    {
      title: '问题',
      key: 'violationCause',
      dataIndex: 'violationCause',
      render: (dom, row) => (
        <>
          <Space wrap>
            {row.violationCause?.map((item) => (
              <Tag color="error">{item}</Tag>
            ))}
          </Space>
        </>
      ),
    },
    {
      title: '媒体',
      key: 'mediaName',
      dataIndex: 'mediaName',
    },
    {
      title: '平台',
      key: 'platformName',
      dataIndex: 'platformName',
    },
    {
      title: '频道',
      key: 'channelName',
      dataIndex: 'channelName',
    },
    {
      title: '发布时间',
      dataIndex: 'releaseTime',
      key: 'releaseTime',
      width: '180px',
      align: 'center',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'articleUrl',
      key: 'articleUrl',
      width: '120px',
      align: 'center',
      search: false,
      render: (dom, entity, index, action, schema) => (
        <a href={entity?.sourceUrl} target="_blank">
          查看原文
        </a>
      ),
    },
  ];

  const loadPageMonitorVideoRecordStatistics = async (queryParam: any) => {
    const response = await pageMonitorVideoRecordStatistics(queryParam);
    if (response.code == 0) {
      setPageMonitorVideoRecordStatisticsDataState(response.data);
    }
  };

  useEffect(() => {
    // loadPageMonitorVideoRecordStatistics({});
    getCascadersMedia();
    getCascadersPlatform();
  }, []);

  return (
    <PageContainer
      style={{ background: '#FFF' }}
      header={{
        breadcrumb: {
          items: [],
        },
        style: {
          paddingBlockEnd: 0,
        },
      }}
      content={
        <RcResizeObserver
          key="resize-observer"
          onResize={(size) => {
            setWidth(size.width);
          }}
        >
          <QueryFilter
            submitter={false}
            span={24}
            labelWidth="auto"
            split
            formRef={formRef}
            initialValues={{
              platformId: '', //渠道=全部
              levelId: '', //媒体=全部
              sourceIds: [], //媒体选择框=空
              // time: '最近90天',
              // releaseTimes: [moment().subtract(89, 'days'), moment()],
            }}
            onFinish={async (value) => {
              if (
                value.sourceIds.length == 0 &&
                value.channelId != 'all' &&
                value.channelId != 'clean'
              ) {
                value.sourceChannelIds = [value.channelId];
              } else {
                value.sourceChannelIds = [];
              }

              if (
                value.sourceIds.length == 0 &&
                value.levelId != 'all' &&
                value.levelId != 'clean'
              ) {
                value.sourceLevelIds = [value.levelId];
              } else {
                value.sourceLevelIds = [];
              }

              if (value.sourceIds != undefined && value.sourceIds.length !== 0) {
                let sourceIds = new Array();

                value.sourceIds.forEach((item: any[]) => {
                  const option = item[item.length - 1];
                  sourceIds.push(option);
                });
                value.sourceIds = sourceIds;
              }
              value.startTime = value.releaseTimes[0];
              value.endTime = value.releaseTimes[1];
              setQueryParamState({ ...queryParam, ...value });
              loadPageMonitorVideoRecordStatistics({ ...queryParam, ...value });
              actionRef.current?.reloadAndRest();
            }}
          >
            <ProForm.Group title="平台">
              <ProFormRadio.Group
                name="platformId"
                radioType="button"
                options={optionsPlatformData}
                fieldProps={{
                  onChange: () => {
                    // formRef.current?.setFieldValue('sourceIds', []);

                    // let levelId = formRef.current?.getFieldValue('levelId');

                    // if (levelId == 'clean') {
                    //   formRef.current?.setFieldValue('levelId', '');
                    // }

                    // getCascadersSource();
                    formRef.current?.submit();
                  },
                }}
              />
              {/* <ProFormRadio.Group
                name="levelId"
                radioType="button"
                options={[
                  { label: '全部', value: 'all' },
                  { label: '市属媒体', value: '2000' },
                  { label: '区县媒体', value: '3000' },
                ]}
                fieldProps={{
                  onChange: () => {
                    formRef.current?.setFieldValue('sourceIds', []);

                    let channelId = formRef.current?.getFieldValue('channelId');

                    if (channelId == 'clean') {
                      formRef.current?.setFieldValue('channelId', 'all');
                    }

                    getCascadersSource();
                    formRef.current?.submit();
                  },
                }}
              /> */}
              <ProFormCascader
                name="sourceIds"
                placeholder="选择媒体"
                fieldProps={{
                  options: optionsCascadersSourceData,
                  style: {
                    width: (width / 3) * 0.95,
                  },
                  multiple: true,
                  removeIcon: true,
                  allowClear: true,
                  showSearch: true,
                  maxTagCount: 'responsive',
                  showCheckedStrategy: Cascader.SHOW_CHILD,
                  onClear() {
                    // formRef.current?.setFieldValue('channelId', 'clean');
                    // formRef.current?.setFieldValue('levelId', 'clean');
                    // getCascadersSource();
                    formRef.current?.submit();
                  },
                  onChange(value, selectOptions) {
                    // let channelId = formRef.current?.getFieldValue('channelId');
                    // let levelId = formRef.current?.getFieldValue('levelId');

                    // if (channelId == 'clean' && levelId == 'clean') {
                    //   formRef.current?.setFieldValue('channelId', 'all');
                    //   formRef.current?.setFieldValue('levelId', 'all');
                    // }

                    // if (value.length > 0) {
                    //   formRef.current?.setFieldValue('channelId', 'clean');
                    //   formRef.current?.setFieldValue('levelId', 'clean');
                    // }

                    formRef.current?.submit();
                  },
                }}
              />
            </ProForm.Group>
            <ProForm.Group title="发布时间">
              <ProFormRadio.Group
                name="time"
                radioType="button"
                options={[
                  { label: '今天', value: '今天' },
                  { label: '本月', value: '本月' },
                  { label: '上月', value: '上月' },
                  { label: '最近7天', value: '最近7天' },
                  { label: '最近60天', value: '最近60天' },
                  { label: '最近90天', value: '最近90天' },
                ]}
                fieldProps={{
                  onChange: () => {
                    const time = formRef.current?.getFieldValue('time');
                    if (time === '今天') {
                      formRef.current?.setFieldValue('releaseTimes', [moment(), moment()]);
                    } else if (time === '本月') {
                      formRef.current?.setFieldValue('releaseTimes', [
                        moment().startOf('month'),
                        moment().endOf('month'),
                      ]);
                    } else if (time === '上月') {
                      formRef.current?.setFieldValue('releaseTimes', [
                        moment().startOf('month').subtract(1, 'months'),
                        moment().endOf('month').subtract(1, 'months'),
                      ]);
                    } else if (time === '最近7天') {
                      formRef.current?.setFieldValue('releaseTimes', [
                        moment().subtract(6, 'days'),
                        moment(),
                      ]);
                    } else if (time === '最近60天') {
                      formRef.current?.setFieldValue('releaseTimes', [
                        moment().subtract(59, 'days'),
                        moment(),
                      ]);
                    } else if (time === '最近90天') {
                      formRef.current?.setFieldValue('releaseTimes', [
                        moment().subtract(89, 'days'),
                        moment(),
                      ]);
                    }
                    formRef.current?.submit();
                  },
                }}
              />
              <ProFormDateRangePicker
                name="releaseTimes"
                fieldProps={{
                  onChange(dates, dateStrings) {
                    formRef.current?.setFieldValue('time', ' ');
                    formRef.current?.submit();
                  },
                }}
              />
            </ProForm.Group>
          </QueryFilter>
        </RcResizeObserver>
      }
    >
      <ProTable<DatahubRecordData.PretreatmentRecordPage>
        cardBordered
        actionRef={actionRef}
        columns={columns}
        request={async (params = {}) => {
          const response = await pageMonitorArticle({
            ...params,
            ...queryParam,
          });

          return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
          });
        }}
        search={false}
        editable={{
          type: 'multiple',
        }}
        rowKey="key"
        options={false}
        toolBarRender={() => [
          <>
            <div
              style={{
                marginTop: 21,
                marginLeft: 10,
              }}
            >
              <RedoOutlined
                onClick={() => {
                  actionRef.current?.reload();
                }}
              />
              <ProFormSwitch
                name="isViolation"
                label="只看问题"
                fieldProps={{
                  onChange: (checked) => {
                    setQueryParamState({ ...queryParam, isViolation: checked ? 1 : 0 });
                    formRef.current?.submit();
                  },
                }}
              />
            </div>
          </>,
        ]}
        toolbar={{
          search: {
            placeholder: '请输入文章标题搜索',
            allowClear: true,
            onSearch: (value: string) => {
              setQueryParamState({ ...queryParam, title: value });
              formRef.current?.submit();
            },
          },
        }}
        // headerTitle={
        //   <div
        //     style={{
        //       display: 'flex',
        //       alignItems: 'center',
        //     }}
        //   >
        //     {/* {pageMonitorVideoRecordStatisticsData &&
        //       pageMonitorVideoRecordStatisticsData.length > 0 && (
        //         <Segmented
        //           name="segmented2"
        //           key="label"
        //           defaultValue={pageMonitorVideoRecordStatisticsData[0]?.label}
        //           options={pageMonitorVideoRecordStatisticsData.map((item) => {
        //             return {
        //               label: (
        //                 <div>
        //                   <div> {item.label}</div>
        //                   <div>{item.value}</div>
        //                 </div>
        //               ),
        //               value: item.label,
        //             };
        //           })}
        //         />
        //       )} */}
        //     {pageMonitorVideoRecordStatisticsData &&
        //       pageMonitorVideoRecordStatisticsData.length > 0 && (
        //         <Descriptions
        //           size="small"
        //           layout="vertical"
        //           bordered
        //           column={
        //             pageMonitorVideoRecordStatisticsData &&
        //             pageMonitorVideoRecordStatisticsData.length
        //           }
        //           labelStyle={{ color: '#CF1322' }}
        //           // style={{backgroundColor:'#FFF1F0'}}
        //           className='description'
        //         >
        //           {pageMonitorVideoRecordStatisticsData.map((item) => (
        //             <Descriptions.Item label={item.label} style={{ textAlign: 'center' }}>
        //               <span style={{ color: '#FF4D4F' }}>{item.value}</span>
        //             </Descriptions.Item>
        //           ))}
        //         </Descriptions>
        //       )}
        //   </div>
        // }
      />
    </PageContainer>
  );
};

export default PageContainerMonitorArticle;
